package config.infra;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;

/**
 *
 * @author yuanj
 * @date 2018/4/18
 */
public abstract class AbstractSessionFactory implements SessionFactory {

  private static final String KEY_ = "FACTORY";

  private final Map<String, SqlSessionFactory> factoryMap = new HashMap<String, SqlSessionFactory>();

  @Override
  public SqlSessionFactory getSqlSessionFactory(Configuration configuration) {
    synchronized (this.factoryMap) {
      if (this.factoryMap.isEmpty()) {
        if (Objects.isNull(configuration)) {
          throw new RuntimeException("configuration must be not null");
        }
        factoryMap.put(KEY_, new DefaultSqlSessionFactory(configuration));
      }
      return factoryMap.get(KEY_);
    }
  }

  @Override
  public  SqlSessionFactory getSqlSessionFactory(String resource) {
    synchronized (this.factoryMap) {
      if (this.factoryMap.isEmpty()) {
        try {
          InputStream inputStream = Resources.getResourceAsStream(resource);
          factoryMap.put(KEY_, new SqlSessionFactoryBuilder().build(inputStream));
        } catch (IOException e) {
        }
      }
      return factoryMap.get(KEY_);
    }
  }
}
